import { Settings2, TestTube2, Volume2, Eye, EyeOff } from 'lucide-react'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Separator } from '@/components/ui/separator'
import { Slider } from '@/components/ui/slider'
import { Switch } from '@/components/ui/switch'
import { useAIAssist } from '@/hooks/useAIAssist'
import { useToast } from '@/hooks/useToast'
import { Badge } from '@/components/ui/badge'
import { IPC_CHANNELS } from 'shared/ipcChannels'
import { Textarea } from '@/components/ui/textarea'
import { PRESET_VOICES } from 'shared/constants'

export default function ConfigCard() {
  const { config, updateConfig, testVoiceConfig } = useAIAssist()
  const { toast } = useToast()
  const [testing, setTesting] = useState(false)
  const [previewing, setPreviewing] = useState(false)
  const [showAccessKeyId, setShowAccessKeyId] = useState(false)
  const [showAccessKeySecret, setShowAccessKeySecret] = useState(false)
  const [showAppKey, setShowAppKey] = useState(false)
  const [customTestText, setCustomTestText] = useState('')

  const handleTestConfig = async () => {
    if (!config.aliyun.accessKeyId || !config.aliyun.accessKeySecret || !config.aliyun.appKey) {
      toast.error('请先配置阿里云 AccessKey ID、AccessKey Secret 和 Appkey')
      return
    }

    setTesting(true)
    try {
      const result = await testVoiceConfig()
      if (result.success) {
        toast.success('配置测试成功！')
      } else {
        toast.error(`配置测试失败: ${result.error}`)
      }
    } catch (err) {
      toast.error('配置测试失败')
    } finally {
      setTesting(false)
    }
  }

  const handlePreviewVoice = async () => {
    if (!config.aliyun.accessKeyId || !config.aliyun.accessKeySecret || !config.aliyun.appKey) {
      toast.error('请先配置阿里云 AccessKey ID、AccessKey Secret 和 Appkey')
      return
    }

    // 检查是否选择了音色
    if (config.voice.type === 'preset' && !config.voice.presetVoiceId) {
      toast.error('请先选择一个预设音色')
      return
    }

    if (config.voice.type === 'clone' && !config.voice.cloneVoiceId) {
      toast.error('请先输入克隆音色 ID')
      return
    }

    setPreviewing(true)
    try {
      const voiceName =
        config.voice.type === 'preset'
          ? PRESET_VOICES.find(v => v.id === config.voice.presetVoiceId)?.name
          : '您的克隆音色'

      // 使用用户自定义文本或默认文本
      const testText = customTestText.trim() 
        || `您好，这是${voiceName}的试听效果，欢迎使用语音播报功能！`

      await window.ipcRenderer.invoke(
        IPC_CHANNELS.tasks.aiAssist.synthesizeVoice,
        {
          text: testText,
          voiceConfig: config,
        },
      )

      toast.success('试听成功！')
    } catch (err) {
      console.error('试听失败:', err)
      toast.error('试听失败，请检查配置')
    } finally {
      setPreviewing(false)
    }
  }

  return (
    <Card className="shadow-sm">
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <div>
            <CardTitle className="flex items-center gap-2">
              <Settings2 className="h-5 w-5" />
              配置设置
            </CardTitle>
            <CardDescription>
              配置阿里云 CosyVoice 和语音播报参数
            </CardDescription>
          </div>
          <Button
            variant="outline"
            size="sm"
            onClick={handleTestConfig}
            disabled={testing}
          >
            <TestTube2 className="h-4 w-4 mr-1" />
            {testing ? '测试中...' : '测试配置'}
          </Button>
        </div>
      </CardHeader>
      <Separator />
      <CardContent className="pt-4 space-y-6">
        {/* 阿里云配置 */}
        <div className="space-y-4">
          <div>
            <h4 className="text-sm font-medium mb-3">阿里云配置</h4>
            <div className="space-y-3">
              <div className="space-y-2">
                <Label htmlFor="accessKeyId">AccessKey ID</Label>
                <div className="relative">
                  <Input
                    id="accessKeyId"
                    type={showAccessKeyId ? 'text' : 'password'}
                    placeholder="请输入阿里云 AccessKey ID"
                    value={config.aliyun.accessKeyId}
                    onChange={e =>
                      updateConfig({
                        aliyun: { ...config.aliyun, accessKeyId: e.target.value },
                      })
                    }
                    className="pr-10"
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                    onClick={() => setShowAccessKeyId(!showAccessKeyId)}
                  >
                    {showAccessKeyId ? (
                      <EyeOff className="h-4 w-4 text-muted-foreground" />
                    ) : (
                      <Eye className="h-4 w-4 text-muted-foreground" />
                    )}
                  </Button>
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="accessKeySecret">AccessKey Secret</Label>
                <div className="relative">
                  <Input
                    id="accessKeySecret"
                    type={showAccessKeySecret ? 'text' : 'password'}
                    placeholder="请输入阿里云 AccessKey Secret"
                    value={config.aliyun.accessKeySecret}
                    onChange={e =>
                      updateConfig({
                        aliyun: { ...config.aliyun, accessKeySecret: e.target.value },
                      })
                    }
                    className="pr-10"
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                    onClick={() => setShowAccessKeySecret(!showAccessKeySecret)}
                  >
                    {showAccessKeySecret ? (
                      <EyeOff className="h-4 w-4 text-muted-foreground" />
                    ) : (
                      <Eye className="h-4 w-4 text-muted-foreground" />
                    )}
                  </Button>
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="appKey">Appkey (语音服务)</Label>
                <div className="relative">
                  <Input
                    id="appKey"
                    type={showAppKey ? 'text' : 'password'}
                    placeholder="请输入智能语音交互应用的 Appkey"
                    value={config.aliyun.appKey}
                    onChange={e =>
                      updateConfig({
                        aliyun: { ...config.aliyun, appKey: e.target.value },
                      })
                    }
                    className="pr-10"
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                    onClick={() => setShowAppKey(!showAppKey)}
                  >
                    {showAppKey ? (
                      <EyeOff className="h-4 w-4 text-muted-foreground" />
                    ) : (
                      <Eye className="h-4 w-4 text-muted-foreground" />
                    )}
                  </Button>
                </div>
                <p className="text-xs text-muted-foreground">
                  在智能语音交互控制台创建项目后获得
                </p>
              </div>
              <div className="space-y-2">
                <Label htmlFor="endpoint">Endpoint (可选)</Label>
                <Input
                  id="endpoint"
                  placeholder="https://nls-gateway.aliyuncs.com/stream/v1/tts"
                  value={config.aliyun.endpoint || ''}
                  onChange={e =>
                    updateConfig({
                      aliyun: { ...config.aliyun, endpoint: e.target.value },
                    })
                  }
                />
                <p className="text-xs text-muted-foreground">
                  默认使用阿里云公共 endpoint，一般无需修改
                </p>
              </div>
            </div>
          </div>

          <Separator />

          {/* 音色选择 */}
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <h4 className="text-sm font-medium">音色选择</h4>
              <Button
                variant="outline"
                size="sm"
                onClick={handlePreviewVoice}
                disabled={previewing}
              >
                <Volume2 className="h-4 w-4 mr-1" />
                {previewing ? '试听中...' : '试听音色'}
              </Button>
            </div>
            <div className="space-y-3">
              <div className="flex items-center gap-4">
                <Label>音色类型</Label>
                <div className="flex gap-2">
                  <Badge
                    variant={
                      config.voice.type === 'preset' ? 'default' : 'outline'
                    }
                    className="cursor-pointer"
                    onClick={() =>
                      updateConfig({ voice: { ...config.voice, type: 'preset' } })
                    }
                  >
                    预设音色
                  </Badge>
                  <Badge
                    variant={
                      config.voice.type === 'clone' ? 'default' : 'outline'
                    }
                    className="cursor-pointer"
                    onClick={() =>
                      updateConfig({ voice: { ...config.voice, type: 'clone' } })
                    }
                  >
                    克隆音色
                  </Badge>
                </div>
              </div>

              {config.voice.type === 'preset' ? (
                <div className="space-y-2">
                  <Label htmlFor="presetVoice">选择预设音色</Label>
                  <Select
                    value={config.voice.presetVoiceId || ''}
                    onValueChange={value =>
                      updateConfig({
                        voice: { ...config.voice, presetVoiceId: value },
                      })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择音色" />
                    </SelectTrigger>
                    <SelectContent>
                      {PRESET_VOICES.map(voice => (
                        <SelectItem key={voice.id} value={voice.id}>
                          {voice.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              ) : (
                <div className="space-y-2">
                  <Label htmlFor="cloneVoice">克隆音色 ID</Label>
                  <Input
                    id="cloneVoice"
                    placeholder="请输入您克隆的音色 ID"
                    value={config.voice.cloneVoiceId || ''}
                    onChange={e =>
                      updateConfig({
                        voice: { ...config.voice, cloneVoiceId: e.target.value },
                      })
                    }
                  />
                  <p className="text-xs text-muted-foreground">
                    您需要先在阿里云控制台克隆声音，然后在此输入音色 ID
                  </p>
                </div>
              )}

              {/* 自定义试听文本 */}
              <div className="space-y-2">
                <Label htmlFor="customTestText">
                  自定义试听文本 (选填)
                </Label>
                <Textarea
                  id="customTestText"
                  placeholder="输入您想要测试的文本内容，留空将使用默认文本..."
                  value={customTestText}
                  onChange={e => {
                    const text = e.target.value
                    if (text.length <= 150) {
                      setCustomTestText(text)
                    }
                  }}
                  className="min-h-[80px] resize-none"
                  maxLength={150}
                />
                <div className="flex justify-between items-center">
                  <p className="text-xs text-muted-foreground">
                    输入自定义文本来试听音色效果
                  </p>
                  <span className="text-xs text-muted-foreground">
                    {customTestText.length}/150
                  </span>
                </div>
              </div>
            </div>
          </div>

          <Separator />

          {/* 播报参数 */}
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <h4 className="text-sm font-medium">播报参数</h4>
              <div className="flex items-center gap-2">
                <Switch
                  checked={config.broadcast.enable}
                  onCheckedChange={checked =>
                    updateConfig({
                      broadcast: { ...config.broadcast, enable: checked },
                    })
                  }
                />
                <Label>启用播报</Label>
              </div>
            </div>

            <div className="space-y-4">
              <div className="space-y-2">
                <div className="flex justify-between">
                  <Label>语速</Label>
                  <span className="text-sm text-muted-foreground">
                    {config.broadcast.speed}x
                  </span>
                </div>
                <Slider
                  value={[config.broadcast.speed]}
                  onValueChange={([value]) =>
                    updateConfig({
                      broadcast: { ...config.broadcast, speed: value },
                    })
                  }
                  min={0.5}
                  max={2.0}
                  step={0.1}
                  disabled={!config.broadcast.enable}
                />
              </div>

              <div className="space-y-2">
                <div className="flex justify-between">
                  <Label>音量</Label>
                  <span className="text-sm text-muted-foreground">
                    {config.broadcast.volume}
                  </span>
                </div>
                <Slider
                  value={[config.broadcast.volume]}
                  onValueChange={([value]) =>
                    updateConfig({
                      broadcast: { ...config.broadcast, volume: value },
                    })
                  }
                  min={0}
                  max={100}
                  step={1}
                  disabled={!config.broadcast.enable}
                />
              </div>

              <div className="space-y-2">
                <div className="flex justify-between">
                  <Label>音调</Label>
                  <span className="text-sm text-muted-foreground">
                    {config.broadcast.pitch}
                  </span>
                </div>
                <Slider
                  value={[config.broadcast.pitch]}
                  onValueChange={([value]) =>
                    updateConfig({
                      broadcast: { ...config.broadcast, pitch: value },
                    })
                  }
                  min={-500}
                  max={500}
                  step={10}
                  disabled={!config.broadcast.enable}
                />
              </div>
            </div>
          </div>

          <Separator />

          {/* 评论过滤 */}
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <h4 className="text-sm font-medium">评论过滤</h4>
              <div className="flex items-center gap-2">
                <Switch
                  checked={config.commentFilter.enableFilter}
                  onCheckedChange={checked =>
                    updateConfig({
                      commentFilter: {
                        ...config.commentFilter,
                        enableFilter: checked,
                      },
                    })
                  }
                />
                <Label>启用过滤</Label>
              </div>
            </div>
            {config.commentFilter.enableFilter && (
              <div className="space-y-2">
                <Label htmlFor="keywords">关键词 (用逗号分隔)</Label>
                <Input
                  id="keywords"
                  placeholder="例如: 产品,价格,优惠"
                  value={config.commentFilter.keywords.join(',')}
                  onChange={e =>
                    updateConfig({
                      commentFilter: {
                        ...config.commentFilter,
                        keywords: e.target.value
                          .split(',')
                          .map(k => k.trim())
                          .filter(Boolean),
                      },
                    })
                  }
                />
                <p className="text-xs text-muted-foreground">
                  只播报包含这些关键词的评论
                </p>
              </div>
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  )
}

